import time

from selenium.webdriver.common.by import By

from common.base import Base
from common.functions import open_browser


# 定义一个ShopCartPage类
class ShopCartPage(Base):
    # 购物车增加操作
    def look_goods(self, locator):
        # 定位一个商品并点击
        self.base_click(locator)

    def buy_goods(self):
        # 定位立即购买，加入购物车
        self.base_click((By.XPATH, '//form[@id="ECS_FORMBUY"]/ul/li[7]/table/tbody/tr/td/a/img'))
        # self.driver.implicitly_wait(10)

    def continue_shop(self):
        # 定位继续购物并点击
        self.base_click((By.XPATH, '//img[@alt="continue"]'))

    # 购物车查看操作
    def check_shopcart(self):
        # 定位购物车并点击
        self.base_click((By.ID, 'ECS_CARTINFO'))

    # 购物车商品数量修改操作
    def clear_goods_num(self):
        # 定位购物车清空商品数量
        self.base_find_element((By.CLASS_NAME, 'inputBg')).clear()

    def modify_goods_num(self, num):
        # 定位购物车增加商品数量
        self.base_find_element((By.CLASS_NAME, 'inputBg')).send_keys(num)

    def update_shopcart(self):
        # 定位更新购物车按钮点击
        self.base_click((By.NAME, 'submit'))

    # 购物车删除并确认删除
    def delete_goods(self):
        # 定位购物车删除按钮点击
        self.base_click((By.LINK_TEXT, '删除'))

    # 切换到弹窗并确认删除
    def alert_accept(self):
        alert = self.driver.switch_to.alert
        alert.accept()

    # 切换到弹窗并取消删除
    def alert_dismiss(self):
        alert = self.driver.switch_to.alert
        alert.dismiss()

    # 定位清空购物车按钮并点击
    def clear_shopcart(self):
        self.base_click((By.XPATH, '//*[@id="formCart"]/table[2]/tbody/tr/td[2]/input[1]'))

    # 点击去结算按钮
    def clearance(self):
        self.base_click((By.XPATH, '//img[@alt="checkout"]'))


if __name__ == '__main__':
    driver = open_browser()
    shop_cart = ShopCartPage(driver)
    shop_cart.base_get('http://139.129.26.163//')
    shop_cart.look_goods((By.XPATH, '//img[@alt="智能相机"]'))
    time.sleep(1)
    shop_cart.buy_goods()
    time.sleep(2)
    shop_cart.clear_goods_num()
    time.sleep(1)
    shop_cart.modify_goods_num(3)
    time.sleep(1)
    shop_cart.delete_goods()
    time.sleep(5)
    # shop_cart.alert_accept()
    # time.sleep(1)
    shop_cart.alert_dismiss()
    time.sleep(1)
    shop_cart.continue_shop()
    time.sleep(1)
    shop_cart.look_goods((By.XPATH, '//img[@alt="炫彩翻页保护套"]'))
    time.sleep(1)
    shop_cart.buy_goods()
    time.sleep(2)
    shop_cart.continue_shop()
    time.sleep(1)
    shop_cart.check_shopcart()
    time.sleep(1)
    shop_cart.update_shopcart()
    time.sleep(3)
    shop_cart.clear_shopcart()
    time.sleep(2)
    driver.quit()
